package com.adingxiong.cft.controller;


import com.adingxiong.cft.cache.LocalCache;
import com.adingxiong.cft.common.FileData;
import com.adingxiong.cft.config.ApplicationProperties;
import com.adingxiong.cft.errors.Assert;
import com.adingxiong.cft.result.Result;
import com.adingxiong.cft.result.RetCode;
import com.adingxiong.cft.service.ITUserService;
import com.adingxiong.cft.util.ExcelToHtml;
import com.adingxiong.cft.util.ExcelTools;
import com.adingxiong.cft.util.HttpUtils;
import com.adingxiong.cft.util.handle.DefHandler;
import com.adingxiong.cft.util.handle.FormulaHandler;
import com.adingxiong.cft.util.handle.InputHandler;
import com.adingxiong.cft.util.handle.SelectHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 邮箱 前端控制器
 * </p>
 *
 * @author xiongc
 * @since 2020-06-18
 */
@RestController
@RequestMapping("/tt")
@Api(tags = "数据导出")
public class UserController {

    @Autowired
    private ApplicationProperties applicationProperties;

    @Autowired
    private ITUserService userService;

    /**
     * 这里的数据返回必须是ResponseEntity类型的
     * @return
     * @throws IOException
     */
    @GetMapping("/uploadExcel")
    public ResponseEntity<byte []> testExportTest() throws IOException {

       HSSFWorkbook wb = modalData();

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        os.flush();

        String fileName ="项目信息导出.xls";
        fileName = new String(fileName.getBytes("utf-8"),"ISO_8859_1");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentDispositionFormData("attachment", fileName);
        return new  ResponseEntity<>(os.toByteArray(),httpHeaders,HttpStatus.OK);
    }

    @GetMapping("/excel/ashtml")
    @ApiOperation(value = "excel转为html页面")
    public Result excelAsHtml(){
        Map<String,String> param = new HashMap<>();
        DefHandler.handlers.put("input",new InputHandler());
        DefHandler.handlers.put("select",new SelectHandler());
        DefHandler.handlers.put("formula",new FormulaHandler());
        HSSFWorkbook wb = modalData();
        return Result.success(ExcelToHtml.getExcelInfo(wb,param,true));
    }


    @ApiOperation(value = "测试application配置文件")
    @GetMapping("/test")
    public String test (){
        return "读取配置文件的值：" + applicationProperties.getSecretKey();
    }


    @GetMapping(value = "/testLog")
    public Result testLog(Integer num){

        int b = 5/num;
        if(b == 1) {
           Assert.fail("不服务");
        }
        return Result.success(b);
    }


    @GetMapping("/cache")
    public Object testCache(String name){
        Object a = LocalCache.getInstance().getValue("name");
        if(a == null){
            LocalCache.getInstance().putValue("name" ,"张三",10);
            return "未读取到缓存数据";
        }
        return "读取到缓存数据,数据为:" + a;
    }

    @GetMapping("/testNet")
    public String testHttp(String url) {
        String res = HttpUtils.doGet(url);
        return res;
    }

    @GetMapping("/exception")
    public void testEexception(String a){
        if(StringUtils.isEmpty(a)){
            Assert.fail("string_a_isNotAll_empty");
        }
        a.split(",");
    }

    private HSSFWorkbook modalData(){
        String  [] excelheader  = {"项目","电话","联系人","金额","负责人","周期"};

        //创建文档对象
        HSSFWorkbook wb = new HSSFWorkbook();
        // 建立新的sheet对象（excel的表单）
        HSSFSheet sheet = wb.createSheet("项目信息统计");
        HSSFRow rowHead = sheet.createRow(0);

        // 创建第一行
        for (int i = 0; i < excelheader.length; i++) {
            rowHead.createCell(i).setCellValue(excelheader[i]);
        }
        HSSFRow row = sheet.createRow(1);
        row.createCell(0).setCellValue("社工协议");
        row.createCell(1).setCellValue("15071384121");
        row.createCell(2).setCellValue("王凯");
        row.createCell(3).setCellValue("500");
        row.createCell(4).setCellValue("周三");
        row.createCell(5).setCellValue("150");
        return wb;
    }

    @GetMapping("/export/word")
    @ApiOperation(value = "根据模板文件导出Word数据")
    public void exportWord(HttpServletResponse response, HttpServletRequest request){
        try {
            userService.exportAsWord(response,request);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.fail("服务异常,导出word失败");
        }
    }


}

